package com.ynding.spring.physical.redis.meta.lock;

import com.ynding.spring.physical.redis.meta.service.RedisService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * <p> redis 分布式锁原理： redis setnx 命令</p>
 *
 * @author ynding
 * @version 2022/6/14
 **/
@Component
@RequiredArgsConstructor
@Slf4j
public class DistributedLock {
    private final RedisService redisService;

    /**
     * 获得锁
     */
    public boolean getLock(String lockId, long millisecond) {
        Boolean success = redisService.getRedisTemplate().opsForValue().setIfAbsent(lockId, "lock",
                millisecond, TimeUnit.MILLISECONDS);
        return success != null && success;
    }

    /**
     * 释放锁
     *
     * @param lockId
     */
    public void releaseLock(String lockId) {
        redisService.getRedisTemplate().delete(lockId);
    }
}
